package server;

import server.container.Service;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ThreadPoolExecutor;

public class ServerProcessor implements  Runnable {

    private Service service;
    private ThreadPoolExecutor threadPoolExecutor;

    public ServerProcessor(Service service, ThreadPoolExecutor threadPoolExecutor) {
        this.service = service;
        this.threadPoolExecutor = threadPoolExecutor;
    }

    @Override
    public void run() {
        ServerSocket serverSocket = null;
        try
        {
            serverSocket = new ServerSocket(service.getConnector().getPort());
            System.out.println(String.format(" ---->> service port %s start",service.getConnector().getPort()));
            while(true){
                try {
                    Socket socket = serverSocket.accept();
                    RequestProcessor requestProcessor = new RequestProcessor(socket, service.getEngine());
                    threadPoolExecutor.execute(requestProcessor);
                }catch(Exception e){
                    e.printStackTrace();
                }

           }
        }
        catch(Exception e){
            e.printStackTrace();
        }finally{
          if(null != serverSocket){
              try {
                  serverSocket.close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
        }
    }
}
